package com.lx.user.web;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.lx.bean.Result;
import com.lx.bilibili.entity.Address;
import com.lx.user.dao.AddressMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController()
@RequestMapping("address")
public class AddressController {

    @Autowired
    AddressMapper addressMapper;

    @RequestMapping("getaddress")
    public Result getaddress(int uid){
        LambdaQueryWrapper<Address> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Address::getUid,uid);
        if (addressMapper.selectList(lqw).size() == 0) {
            return new Result(0, "暂无地址",null);
        }else {
            return new Result(1, "查询成功",addressMapper.selectList(lqw));
        }
    }

    @RequestMapping("saveAddress")
    public Result saveAddress(@RequestBody Address address){
        System.out.println("address = " + address);
        if(address.getIsDefaultAddress().equals("true")){
            LambdaUpdateWrapper<Address> luw = new LambdaUpdateWrapper<>();
            luw.set(Address::getIsDefaultAddress,"false").eq(Address::getUid,address.getUid()).eq(Address::getIsDefaultAddress,"true");
            addressMapper.update(address,luw);
        }
        return new Result(1, "添加成功", addressMapper.insert(address));
    }

    @RequestMapping("updateAddress")
    public Result updateAddress(@RequestBody Address address){
        return new Result(1, "修改成功", addressMapper.updateById(address));
    }

    @RequestMapping("deleteAddress")
    public Result deleteAddress(int id){
        LambdaQueryWrapper<Address> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Address::getId,id);
        return new Result(1, "删除成功", addressMapper.delete(lqw));
    }

    @RequestMapping("getDefultAddress")
    public Result getDefultAddress(int uid){
        LambdaQueryWrapper<Address> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Address::getUid,uid);
        lqw.eq(Address::getIsDefaultAddress,"true");
        Address addressList = addressMapper.selectOne(lqw);
        if (addressList == null) {
            return new Result(0, "暂无默认地址",null);
        }else {
            return new Result(1, "查询成功",addressList);
        }
    }
}
